<template>
  <div>
    <!-- 增加产品项目 -->
    <Dialog :title="title" :visible="show" class="two-columns" :button-text="testBtn" :loading="loading" @confirm="submitForm" @close="handleClose">
      <div class="dialog-magin-y">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" label-position="right">
          <el-col :span="12" prop="specifications">
            <el-form-item label="规格：">
              <el-input v-model="ruleForm.specifications" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称：" prop="name">
              <el-input v-model="ruleForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位：" prop="unit">
              <el-select v-model="ruleForm.unit" placeholder="请选择单位" class="el-select-y">
                <el-option label="个" value="个" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="打印名称：" prop="printName">
              <el-input v-model="ruleForm.printName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用次数：" prop="usageTimes">
              <el-input v-model="ruleForm.usageTimes" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拼音码：" prop="PYM">
              <span>系统自动生成</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目期限：" prop="projectDuration">
              <el-input v-model="ruleForm.projectDuration" style="width:94%" />天
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品属性：" prop="productAttributes">
              <el-select v-model="ruleForm.productAttributes" placeholder="请选择产品属性" class="el-select-y">
                <el-option v-for="item in propertyOptions" :key="item.id" :label="item.value" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目售价：" prop="price">
              <el-input v-model="ruleForm.price" style="width:94%" @change="discountChange(ruleForm)" />元
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品分类：" prop="productClassificationId">
              <el-cascader :value="ruleForm.productClassificationType" :options="productClassifications" :props="propsOption" clearable class="el-select-y" @change="classificationContent" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣下限：" prop="discount">
              <el-input v-model="ruleForm.discount" style="width:94%" @change="discountChange(ruleForm)" />%
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="划扣部门：" prop="deductionDeptId">
              <el-cascader :value="ruleForm.deductionDept" :options="depts" :props="deptOption" clearable class="el-select-y" @change="deptContent" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-input v-model="discountPrice" style="width:94%" @change="discountPriceChange(ruleForm)" />元
            </el-form-item>
          </el-col>
          <!-- <el-row>
            <el-col :span="24">
              <el-collapse value="goods" accordion>
                <el-collapse-item name="goods">
                  <template slot="title"> 绑定耗材 </template>
                  <data-table
                    ref="dataTable"
                    :load-data="loadData"
                    style="width: 100%;margin-bottom: 20px;"
                    row-key="id"
                    border
                    stripe
                    @selection-change="handleCheckChange"
                  >
                    <el-table-column type="selection" reserve-selection align="center" width="50" />
                    <el-table-column type="index" width="50" align="center" label="序号" />
                    <el-table-column label="物品编号" width="200" prop="no" />
                    <el-table-column label="物品名称" width="200" prop="name" />
                    <el-table-column label="物品分类" prop="productClassificationName" />
                  </data-table>
                </el-collapse-item>
              </el-collapse>
            </el-col>
          </el-row> -->
          <el-col :span="12">
            <el-form-item label="状态：" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio label="上架" />
                <el-radio label="下架" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联耗材：" prop="selected">
              <el-row v-for="(json,index) in selected" :key="index" style="padding-bottom: 18px;">
                <el-select v-model="json.id" filterable placeholder="请选择物品/药品" class="el-select-y select-display">
                  <el-option v-for="item in dataList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-input v-model="json.goodsNum" onkeyup="this.value=this.value.replace(/\D/g,'')" class="input-display" />
                <el-button v-if="index !== 0" type="text" class="font-color1" @click="deletebinding(index)">- 删除</el-button>
              </el-row>
              <el-button type="text" class="font-color" @click="addbinding">+ 增加</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
    </Dialog>
  </div>
</template>
<script>
import Dialog from '@/components/Dialog';
export default {
  components: {
    Dialog,
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      propertyOptions: [
        {
          id: "美容项目",
          value: "美容项目",
        },
        {
          id: "手术项目",
          value: "手术项目",
        },
        {
          id: "检查项目",
          value: "检查项目",
        },
        {
          id: "其他项目",
          value: "其他项目",
        },
      ],
      productClassifications: [],
      depts: [],
      ruleForm: {
        status: "上架",
      },
      title: '',
      testBtn: '保存',
      loading: false,
      discountPrice: '',
      // visible: false,
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入项目售价', trigger: 'blur' },
        ],
        usageTimes: [
          { required: true, message: '请输入产品使用次数', trigger: 'blur' },
        ],
        productAttributes: [
          { required: true, message: '请选择项目属性', trigger: 'change' },
        ],
        // projectDuration: [
        //   { required: true, message: '请输入项目期限', trigger: 'blur' },
        // ],
        // productClassificationId: [
        //   { required: true, message: '请选择产品分类', trigger: 'change' },
        // ],
        // deductionDeptId: [
        //   { required: true, message: '请选择划扣部门', trigger: 'change' },
        // ],
      },
      propsOption: {
        value: 'id',
        label: 'dataName',
        checkStrictly: true,
      },
      deptOption: {
        value: 'id',
        label: 'deptName',
        checkStrictly: true,
      },
      selected: [{ goodsNum: 0 }],
      dataList: [],
    };
  },
  mounted() {
    this.getProductClassifications();
    this.getDepts();
    // this.$nextTick(() => {
    // this.handleQuery();
    // this.loadSelectedData();
    // });
    this.getList();
  },
  methods: {
    async getList() {
      const res = await this.$api['data/drugs/drugsList']({ query: { type: "物品,药品", inventory: "进货" }});
      if (res.code !== 200) return this.$message.error(res.mag);
      this.dataList = res.data;
    },
    addBtn() {
      this.title = '增加产品';
      this.ruleForm.id = undefined;
    },
    handleQuery() {
      this.$refs.dataTable.reload({ query: { type: "物品" }});
    },
    editBtn(row) {
      if (row && row.id) {
        this.ruleForm = JSON.parse(JSON.stringify(row));
        if (this.ruleForm.price && this.ruleForm.discount) {
          this.discountPrice = ((this.ruleForm.price * this.ruleForm.discount) / 100).toFixed(2);
        }
        if (this.ruleForm.allProductClassificationId) {
          this.ruleForm.productClassificationType = this.ruleForm.allProductClassificationId.split(",");
        }
        console.log(this.ruleForm.allDeductionDeptId);
        if (this.ruleForm.allDeductionDeptId) {
          this.$set(this.ruleForm, 'deductionDept', this.ruleForm.allDeductionDeptId.split(","));
        }
        if (row.goodsList && row.goodsList.length > 0) {
          this.selected = row.goodsList;
        } else {
          this.selected = [{ goodsNum: 0 }];
        }
        // this.selected = this.loadData({ projectIds: [row.id] });
      }
      this.title = '编辑产品';
    },
    // 保存
    submitForm() {
      this.$refs.ruleFormRef.validate(valid => {
        if (!valid) return;
        const pinyinCode = this.$pinyin(this.ruleForm.name, { style: this.$pinyin.STYLE_NORMAL, heteronym: true });
        this.ruleForm.pinyinCode = "";
        pinyinCode.forEach(item => {
          this.ruleForm.pinyinCode += item;
        });
        this.loading = true;
        const list = [];
        let isTrue = false;
        let msg = "";
        this.selected.forEach(item => {
          if (item.id && item.goodsNum) {
            list.push(item);
          } else if (!item.id && this.selected.length > 1) {
            isTrue = true;
            msg = "请选择关联耗材名字";
          } else if (!item.goodsNum && this.selected.length > 1) {
            isTrue = true;
            msg = "请输入关联耗材数量";
          }
        });
        if (isTrue) {
          this.$message.error(msg);
          this.loading = false;
          return;
        }
        if (list.length > 0) {
          this.$set(this.ruleForm, 'goodsList', list);
        }
        if (this.ruleForm.id) {
          this.$api['data/projects/editList']({
            ...this.ruleForm,
          }).then(res => {
            if (res.code !== 200) return;
            this.$emit('success');
            this.msgSuccess('修改项目成功');
            this.handleClose();
          }).finally(() => (this.loading = false));
        } else {
          this.$api['data/projects/addList']({
            ...this.ruleForm,
          }).then(res => {
            if (res.code !== 200) return;
            this.$emit('success');
            this.msgSuccess('增加项目成功');
            this.handleClose();
          }).finally(() => {
            this.$parent.getAddProjectList();
            (this.loading = false);
          });
        }
      });
    },
    handleClose() {
      this.$refs.ruleFormRef.resetFields();
      this.$emit('update:show', false);
      this.ruleForm = {};
      // this.$refs.ruleFormRef.resetFields();
    },
    getProductClassifications() {
      this.$api['data/projects/sortTree']({
        dataType: '项目类',
      }).then(res => {
        if (res.code !== 200) return;
        this.productClassifications = res.data;
      });
    },
    classificationContent(val) {
      const content = [];
      let list = JSON.parse(JSON.stringify(this.productClassifications));
      val.forEach(id => {
        const item = this.getClassificationContent(id, list);
        content.push(item.name);
        list = item.list;
      });
      this.ruleForm.productClassification = content.join("/");
      this.ruleForm.productClassificationId = val[val.length - 1];
      this.ruleForm.allProductClassificationId = val.join(",");
    },
    getClassificationContent(id, list) {
      const json = {};
      list.forEach(item => {
        if (item.id === id) {
          json.name = item.dataName;
          json.list = item.children;
        }
      });
      return json;
    },
    getDepts() {
      this.$api['data/projects/deptTree']().then(res => {
        if (res.code !== 200) return;
        console.log("res.data", res.data);
        this.depts = res.data;
      });
    },
    deptContent(val) {
      console.log(val);
      const content = [];
      let list = JSON.parse(JSON.stringify(this.depts));
      val.forEach(id => {
        const item = this.getDeptContent(id, list);
        content.push(item.name);
        list = item.list;
      });
      this.ruleForm.deductionDeptName = content.join("/");
      this.ruleForm.deductionDeptId = val[val.length - 1];
      this.ruleForm.allDeductionDeptId = val.join(",");
    },
    getDeptContent(id, list) {
      const json = {};
      list.forEach(item => {
        if (item.id === id) {
          json.name = item.deptName;
          json.list = item.children;
        }
      });
      return json;
    },
    discountChange(val) {
      if (val.price && val.discount) {
        this.discountPrice = ((val.price * val.discount) / 100).toFixed(2);
        return;
      }
      if (val.price && this.discountPrice !== '') {
        this.$set(this.ruleForm, 'discount', ((this.discountPrice / this.ruleForm.price) * 100).toFixed(2));
      }
    },
    discountPriceChange(val) {
      if (val.price) {
        this.$set(this.ruleForm, 'discount', ((this.discountPrice / this.ruleForm.price) * 100).toFixed(2));
      }
    },
    loadData(queryParams) {
      return new Promise((resolve, reject) => {
        this.$api['data/drugs/drugsListPage'](queryParams)
          .then(resData => {
            resolve(resData);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    handleCheckChange(s) {
      this.selected = s;
    },
    loadSelectedData() {
      // 加载选中的耗材
      this.$api['data/projects/ProjectGoods']({ projectId: this.ruleForm.id })
        .then(resData => {
          this.toggleSelection(resData.data);
        })
        .catch(err => {
          // this.$message.error('添加划扣失败!');
          console.error(err);
        });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.dataTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.dataTable.clearSelection();
      }
    },
    addbinding() {
      const json = { goodsNum: 0 };
      this.selected.push(json);
    },
    async deletebinding(index) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      } else {
        this.selected.splice(index, 1);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
// .dialog-magin-y{
//   margin: 0 150px;
// }
.el-select-y.el-cascader{
  width: 100%;
}
.select-display{
  width: 138px;
  float: left;
}
.input-display{
  width: 55px;
  margin-left: 10px;
  float: left;
}
.font-color{
  color:#0278DC;
}
.font-color1{
  color: #A30014;
}
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
